﻿using CKS.Core.Framework;
using FreeSql;
using Infrastructure;
using Infrastructure.Extensions;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Models.ProductionControl;
using ZR.ServiceCore.Services;

namespace CKS.PLC.Action.System {
    /// <summary>
    /// 执行通用数据采集方法类 
    /// </summary>
    public class SaveProcessingResultsAction : PLCAction {
        /// <summary>
        /// 作用类型是加工结果，保存数据到1张表里
        /// </summary>
        public SaveProcessingResultsAction(DecodeValue value) : base(value) {

        }

        /// <summary>
        /// 通用追溯
        /// 根据点位关联的 PlcId\ActionId\ActionKey 查询到动作关联的表
        /// </summary>
        public override void Execute(Dictionary<string, object> execParams) {

            using (var ObjectCo = base.FreeSql.Ado.MasterPool.Get()) {
                var conn = ObjectCo.Value;
                var position = DecodeValue.Position;
                var act = conn.Select<CksPlcActions>()
                    .Where(a => a.ActionType == 1
                            && a.PlcId == position.PlcId
                            && a.ActionId == position.ActionId
                            && a.ActionKey == position.ActionKey
                            && a.ReadDB == position.BlockDb
                            )
                    .First();

                //1.获取请求结果
                var result = DecodeValue.Value.ToInt();

                //2.获取回复点位
                var replyPos = DecodeValue.GetReplyPosition(act.WriteDB, act.ActionId, position.ActionKey);

                if (result == 1) {
                    //获取虚拟表和列信息
                    var vTable = conn.Select<CksVirtualTable>().Where(a => a.Id == act.BusinessId).First();
                    var vColumns = conn.Select<CksVirtualColumn>().Where(a => a.TableId == act.BusinessId).OrderBy(a => a.Sequence).ToList();

                    //获取主码的值
                    var primaryCodeValue = GetMainCodeValue();
                    //采集批次
                    string batchNo = execParams.GetValueOrDefault(BasePlcAction._execBatchCodeKey)?.ToString();
                    execParams.Add("TestCode", primaryCodeValue);

                    //索引优化后缀（采集批次）
                    string batchSuffix = GetSuffix(batchNo, 5);

                    //索引优化后缀（主产品码）
                    string mainCodeSuffix = GetSuffix(primaryCodeValue);

                    //获取当前表格的最大虚拟Id                            
                    vTable.MaxSeqId = GetNextSeq(vTable, conn);

                    CksCollected collectInfo = new CksCollected() {
                        PrimaryCode = primaryCodeValue,
                        Suffix_4 = mainCodeSuffix,
                        BatchCode = batchNo,
                        BatchSuffix = batchSuffix,
                        CreatedTime = DateTime.Now,
                        PlcId = act.PlcId,
                        ReadDB = act.ReadDB,
                        SequenceId = vTable.MaxSeqId,
                        TableId = vTable.Id,
                        Nullity = false,
                    };
                    List<CksCollectedDetails> collectDtl = new List<CksCollectedDetails>();
                    //创建实体表字典列数据
                    var dicColData = new Dictionary<string, object>();
                    dicColData.Add("PlcId", act.PlcId);
                    dicColData.Add("BlockDb", act.ReadDB);
                    dicColData.Add("CollectBatchCode", batchNo);
                    //遍历采集项
                    foreach (var item in vColumns) {
                        //获取当前配置的【数据ID】对应的【点位】数据
                        var data = DecodeValue.GetLinkDecodeObject(item.DataId);
                        string content = data.IsCharArray ? data.CharString : data.Value.ToString();

                        //主码字段处理
                        if (item.IsPrimary) {
                            content = primaryCodeValue;
                        }

                        //节拍字段处理
                        if (item.IsCycleTime) {
                            collectInfo.CycleTime = content.ToInt();
                        }

                        //结果字段处理
                        if (item.IsResult) {
                            collectInfo.Result = content.ToInt();
                        }

                        //批次字段处理
                        if (item.IsBatchCode) {
                            var curUseBatchCode = conn.Select<CksBatchCodeData>().Where(o => o.PlcId == position.PlcId && o.DbBlock == position.BlockDb && o.Type == item.DataId && !o.Nullity).ToList().LastOrDefault();
                            content = curUseBatchCode != null ? curUseBatchCode.BatchCode : string.Empty;
                        }

                        var model = new CksCollectedDetails() {
                            Content = content,
                            ColumnName = item.ColumnName,
                            ColumnId = item.Id,
                            PlcId = act.PlcId,
                            TableId = vTable.Id,
                            BatchSuffix = batchSuffix,
                            BatchCode = batchNo,
                            CreatedTime = collectInfo.CreatedTime
                        };

                        collectDtl.Add(model);
                        dicColData.Add(item.ColumnName, content);
                    }
                    dicColData.Add("CreateTime", DateTime.Now);
                    dicColData.Add("Nullity", $"0");

                    conn.Insert(collectDtl).ExecuteAffrows();//新增采集明细
                    conn.Insert(collectInfo).ExecuteAffrows();//新增采集主表
                    conn.Update<CksVirtualTable>().SetSource(vTable).UpdateColumns(a => a.MaxSeqId).ExecuteAffrows();//更新虚拟表最大序列号
                    var res = base.FreeSql.InsertDict(dicColData).AsTable(vTable.TableName).ExecuteAffrows();//新增实体表数据

                    //回复保存完成信号
                    WriteInt16(replyPos, 1);
                    WriteLogUI($"数据保存完成");

                } else if (result == 0) {
                    //复位上位机的信号
                    WriteInt16(replyPos, 0);
                    WriteLogUI($"数据保存重置");
                }
            }

        }

        public override void ExecuteAfter(Dictionary<string, object> execParams) {

            using (var ObjectCo = base.FreeSql.Ado.MasterPool.Get()) {
                var conn = ObjectCo.Value;
                var position = DecodeValue.Position;
                var result = DecodeValue.Value.ToInt();

                if (result == 1) {

                    //获取主码的值
                    var primaryCodeValue = GetMainCodeValue();
                    //采集批次
                    string batchNo = execParams.GetValueOrDefault(_execBatchCodeKey)?.ToString();

                    #region 更新加工时间
                    //如果是主码，则需要更新工件记录ID
                    var collectInfo = conn.Select<CksCollected>()
                        .Where(o => o.PrimaryCode == primaryCodeValue && o.PlcId == position.PlcId && o.ReadDB == position.BlockDb && o.BatchCode == batchNo)
                        .ToList().LastOrDefault();
                    var workRec = conn.Select<CksWorkRecord>().Where(o => o.PrimaryCode == collectInfo.PrimaryCode && o.PlcID == position.PlcId && o.ReadDB == position.BlockDb).ToList().LastOrDefault();
                    if (workRec != null) {
                        conn.Update<CksCollected>()
                             .Set(o => o.WorkRecId, workRec.Id)
                             .Where(o => o.PrimaryCode == primaryCodeValue && o.PlcId == position.PlcId && o.ReadDB == position.BlockDb && o.BatchCode == batchNo)
                             .ExecuteAffrows();
                    }
                    #endregion

                    #region 更新采集曲线的批次号
                    //散热片OP60-1、OP60-2、OP60-3工站采集压力曲线
                    if (position.PlcId == 139 || position.PlcId == 148 || position.PlcId == 149) {
                        conn.Update<CksCollectedCurveData>()
                             .Set(o => o.CollectBatchCode, batchNo)
                             .Where(o => o.PrimaryCode == primaryCodeValue && o.PlcId == position.PlcId && o.DbBlock == position.BlockDb && string.IsNullOrEmpty(o.CollectBatchCode))
                             .ExecuteAffrows();
                    }
                    #endregion

                    #region 执行托盘码解绑
                    var sysConfigService = App.GetService<ISysConfigService>();
                    var configValue = sysConfigService.GetSysConfigByKey("unbindpalletcode");
                    var plcIDs = configValue.ConfigValue.Split(",");
                    if (plcIDs.Any(o => o == position.PlcId.ToString())) {

                        var barRelRec = conn.Select<CksBarcodeRelationshipRecord>().Where(o => o.Type == ZR.Model.Enums.eBarCodeRelType.PalletCode && o.PrimaryCode == primaryCodeValue).ToList().LastOrDefault();
                        if (barRelRec != null) {
                            barRelRec.IsDeleted = true;
                            var affRows = conn.Update<CksBarcodeRelationshipRecord>()
                                .SetSource(barRelRec)
                                .UpdateColumns(o => o.IsDeleted)
                                .ExecuteAffrows() > 0;
                            WriteLogUI($"托盘关系解绑，结果：{affRows}");
                        } else {
                            WriteLogUI($"托盘关系解绑，未查询到绑定关系，结果：False");
                        }
                    }
                    #endregion

                }
            }
        }



    }
}
